package com.sky.earnmoney;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;

import com.sky.earnmoney.api.Api;
import com.sky.earnmoney.api.HttpResult;
import com.sky.earnmoney.api.NetWorkUtils;
import com.sky.earnmoney.api.UserManager;
import com.sky.earnmoney.bean.IndexData;
import com.sky.earnmoney.bean.ResultSeckill;
import com.sky.earnmoney.ui.login.LoginActivity;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author: xuzhiyong
 * @date: 2022/1/26  下午11:28
 * @Email: 18971269648@163.com
 * @description:
 */
public class MainActivity extends AppCompatActivity {


    String token;
    int category_id = 40;
    TextView showView;
    TextView text_timer;
    TextView text_view_log;
    EditText edit_token;
    EditText edit_category;
    EditText edit_goodsNum;
    NestedScrollView layout_log;
    Button btn_view_refresh;
    Button btn_view;
    GoodsListInfo.DataBean minBean;
    List<GoodsListInfo.DataBean> minList;
    GoodsDetail goodsInfo;
    Api api;
    LoadingDialog loadingDialog;
    StringBuffer buffer = new StringBuffer("本次日志记录:\n");
    Handler handler = new Handler();

    private void println(String msg){
        buffer.append(msg);
        buffer.append("\n");
        showView.post(new Runnable() {
            @Override
            public void run() {
                text_view_log.setText(buffer.toString());
                layout_log.scrollBy(0,text_view_log.getHeight());
            }
        });

    }

    private Runnable sendRequest = new Runnable() {
        @Override
        public void run() {
            clickToGetMoney(null);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        loadingDialog = new LoadingDialog(this);
        showView = findViewById(R.id.text_view);
        text_timer = findViewById(R.id.text_timer);
        text_view_log = findViewById(R.id.text_view_log);
        edit_token = findViewById(R.id.edit_token);
        edit_category = findViewById(R.id.edit_category);
        edit_goodsNum = findViewById(R.id.edit_goodsNum);
        btn_view = findViewById(R.id.btn_view);
        btn_view_refresh = findViewById(R.id.btn_view_refresh);
        layout_log = findViewById(R.id.layout_log);


        if(!UserManager.getInstance().isLogined()){
            startActivity(new Intent(this, LoginActivity.class));
        }
        token = UserManager.getInstance().getToken();
        edit_token.setText("token:"+token);

        api = NetWorkUtils.getInstance().getApi();

       request();
    }

    private void request() {

        HashMap<String, Object> indexMap = new HashMap<>();
        indexMap.put("token",token);
        println("index 获取场次信息开始 token："+ token);
        //获取场次
        api.indexData(indexMap).enqueue(new Callback<HttpResult<IndexData>>() {
            @Override
            public void onResponse(Call<HttpResult<IndexData>> call, Response<HttpResult<IndexData>> response) {
                println("获得场次信息数据返回");
                if(response.isSuccessful()){
                    println("获得场次信息数据成功");
                    HttpResult<IndexData> dataHttpResult = response.body();
                    IndexData data = dataHttpResult.data;
                    List<ResultSeckill> resultSeckill = data.getResultSeckill();
                    int count = 0;
                    if(resultSeckill != null && resultSeckill.size() > 0){
                        for (int i = 0; i < resultSeckill.size(); i++) {
                            ResultSeckill seckill = resultSeckill.get(i);
                            long start_time = seckill.getStart_time();
                            long currentTimeMillis = System.currentTimeMillis() / 1000;
                            if(currentTimeMillis > seckill.getEnd_time()){
                                count++;
                                continue;
                            }

                            category_id = seckill.getId();
                            edit_category.setText(seckill.getCategory_name()+":id="+category_id);

                            if(currentTimeMillis < start_time){
                                //未开始进行倒计时定时
                                startTimerToClick(start_time - currentTimeMillis);
                           }
                            break;
                        }
                    }

                    println("拿到当前场次id="+category_id);
                    if(count == resultSeckill.size()){
                        println("当日场次已结束");
                        Toast.makeText(MainActivity.this,"当日场次已结束",Toast.LENGTH_SHORT).show();
                        loadingDialog.close();
                        return;
                    }

                    fetchListInfo();
                }

            }

            @Override
            public void onFailure(Call<HttpResult<IndexData>> call, Throwable t) {
                println("获取场次信息失败 error:"+t.getMessage());
                Toast.makeText(MainActivity.this,"error "+t.getMessage(),Toast.LENGTH_SHORT).show();
                btn_view.setEnabled(false);
            }
        });




    }

    private int ticks = 0;

    private void startTimerToClick(long time) {
        //减20000 是提前2秒开始的意思
        new CountDownTimer(time * 1000 - 20000,1000){
            @Override
            public void onTick(long millisUntilFinished) {
                text_timer.setText(formatTime(millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                text_timer.setText("抢单中...");
                clickToGetMoney(null);
            }
        }.start();
    }

    public static String formatTime(long time){

        long hh = time/3600;
        long mm = (time-3600*hh)/60;
        long ss = (time-3600*hh-60*mm);

        StringBuilder sb = new StringBuilder();

        sb.append(hh+"时");
        if(mm<10){
            sb.append("0"+mm+"分");
        }else{
            sb.append(mm+"分");
        }

        if(ss<10){
            sb.append("0"+ss+"秒");
        }else{
            sb.append(ss+"秒");
        }

        return sb.toString();

    }


    private void fetchListInfo(){
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("page",1);
        hashMap.put("limit",6000);
        hashMap.put("category_id",category_id);
        hashMap.put("sort","all");
        hashMap.put("token",token);
        println("开始获取列表信息开始 token:"+ token);
        api.getGoodsList(hashMap).enqueue(new Callback<GoodsListInfo>() {
            @Override
            public void onResponse(Call<GoodsListInfo> call, Response<GoodsListInfo> response) {
                loadingDialog.close();
                println("获取列表信息成功");
                GoodsListInfo goodsListInfo = response.body();
                if(goodsListInfo != null && goodsListInfo.getData() != null && goodsListInfo.getData().size() > 0){
                    //商品列表
                    List<GoodsListInfo.DataBean> goodsList = goodsListInfo.getData();
                    if(goodsList != null && goodsList.size() > 0){
                        //获取最小的bean
                        minBean = goodsList.get(0);
                        double minPrice = minBean.getPrice();
                        for (int i = 1; i < goodsList.size(); i++) {
                            if(minPrice > goodsList.get(i).getPrice()){
                                minPrice = goodsList.get(i).getPrice();
                                minBean = goodsList.get(i);
                            }
                        }
                        println("获取最小金额商品:\n id="+minBean.getId() + "\n 编号："+ minBean.getGoods_num() + "\n 商品名："+ minBean.getGoods_name()+"\n price:"+minPrice);
                        minList = new ArrayList<>();

                        StringBuilder builder = new StringBuilder("最小金额商品集合：\n");
                        for (int i = 0; i < goodsList.size(); i++) {
                            if(goodsList.get(i).getPrice() == minBean.getPrice()){
                                minList.add(goodsList.get(i));
                                builder.append("商品id："+goodsList.get(i).getId());
                                builder.append("\n");
                                builder.append("商品编号："+goodsList.get(i).getGoods_num());
                                builder.append("\n");
                                builder.append("商品名称："+goodsList.get(i).getGoods_name());
                                builder.append("\n");
                                builder.append("金额："+goodsList.get(i).getPrice());
                                builder.append("\n");
                                builder.append("所需百佳通："+goodsList.get(i).getCharge_price());
                                builder.append("\n");
                                builder.append("\n");
                            }
                        }

                        println("获取最小金额商品集合成功共 "+minList.size() +" 条数据");
                        showView.setText(builder.toString());

                        //默认抢单一次
                        clickToGetMoney(null);

                        //然后获取详情信息
                        HashMap<String, Object> infoMap = new HashMap<>();
                        infoMap.put("id",minBean.getId());
                        infoMap.put("token",token);

                        println("获取最小金额商品：\n"+minBean.getGoods_name()+" \nid="+minBean.getId() +" \n token="+token);
                        api.getGoodsInfo(infoMap).enqueue(new Callback<GoodsDetail>() {
                            @Override
                            public void onResponse(Call<GoodsDetail> call, Response<GoodsDetail> response) {
                                goodsInfo = response.body();
                                btn_view.setEnabled(true);
                                println("获取最小金额商品信息成功");
                            }

                            @Override
                            public void onFailure(Call<GoodsDetail> call, Throwable t) {
                                Toast.makeText(MainActivity.this,"error "+t.getMessage(),Toast.LENGTH_SHORT).show();
                                btn_view.setEnabled(false);
                            }
                        });

                    }
                }else{
                    Toast.makeText(MainActivity.this,"error "+goodsListInfo.getMsg(),Toast.LENGTH_SHORT).show();
                    btn_view.setEnabled(false);
                }
            }

            @Override
            public void onFailure(Call<GoodsListInfo> call, Throwable t) {
                println("开始获取列表信息失败");
                Toast.makeText(MainActivity.this,"error "+t.getMessage(),Toast.LENGTH_SHORT).show();
                btn_view.setEnabled(false);
                loadingDialog.close();
            }
        });
    }


    /**
     *
     * @param view
     */
    public void clickToGetMoney(View view) {
        //发起抢单
        println("发起抢单 token="+token);
        loadingDialog.show();
        if(!TextUtils.isEmpty(edit_goodsNum.getText().toString())){
            println("发起抢单 指定商品编号抢单id=" + edit_goodsNum.getText().toString());
            GoodsListInfo.DataBean dataBean = new GoodsListInfo.DataBean();
            try {
                dataBean.setId(Integer.valueOf(edit_goodsNum.getText().toString()));
                dataBean.setGoods_name("指定商品");
                dataBean.setGoods_num("指定商品");
                sendRequest(dataBean);
                return;
            }catch (Exception e){
                println("发起抢单 指定商品编号抢单Error" +e.getMessage());
                Toast.makeText(this,"指定商品编号抢单Error"+ e.getMessage(),Toast.LENGTH_SHORT).show();
            }
        }

        if(minList != null && minList.size() > 0){
            //多个商品并行抢单
            for (int i = 0; i < minList.size(); i++) {
                println("发起抢单 商品开始:" +minList.get(i).getGoods_num() +" "+ minList.get(i).getGoods_name());
                sendRequest(minList.get(i));
            }
        }
    }

    private void sendRequest(GoodsListInfo.DataBean minBean){
        final Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //单个商品抢单，次数设置 200 * 50  10sconds  单个商品抢单持续时长，50ms一次，共两百次，持续10秒钟
                for (int i = 0; i < 200; i++) {
                    final int nums = i + 1;
                    HashMap<String, Object> requestMap = new HashMap<>();
                    requestMap.put("id",minBean.getId());
                    requestMap.put("token",token);
                    println("发起抢单\n 商品次数:\n" +minBean.getGoods_num() +"\n "+ minBean.getGoods_name() + " 次数："+ nums);
                    api.request(requestMap).enqueue(new Callback<HttpResult<Object>>() {
                        @Override
                        public void onResponse(Call<HttpResult<Object>> call, Response<HttpResult<Object>> response) {
                            loadingDialog.close();
                            if(response.isSuccessful() && response.body().code == 0){
                                //抢单成功
                                println("抢单成功");
                                Toast.makeText(MainActivity.this,"抢单成功，快去支付",Toast.LENGTH_SHORT).show();
                            }else{
                                //抢单失败
                                if(response.isSuccessful()){
                                    println("抢单失败:\n"+ response.body().msg+" \n商品次数:" +minBean.getGoods_num() +"\n "+ minBean.getGoods_name() + " 次数："+ nums);
                                }else{
                                    println("抢单失败:\n"+ response.message() +"\n 商品次数:" +minBean.getGoods_num() +"\n "+ minBean.getGoods_name() + " 次数："+ nums);
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<HttpResult<Object>> call, Throwable t) {
                            println("抢单异常:\n"+ t.getMessage()+" \n商品次数:" +minBean.getGoods_num() +"\n "+ minBean.getGoods_name() + " 次数："+ nums);
                        }
                    });

                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    }

    public void refresMin(View view) {
        loadingDialog.setLoadingText("加载中。。。").show();
        request();
    }
}
